﻿Imports System
Imports System.IO
Imports System.IO.Ports
Imports System.Threading
Imports System.Threading.Thread

Public Class Form1
    Dim SpaceCount As Byte = 0
    Dim LookUpTable As String = "0123456789ABCDEF"
    Dim RXArray(2047) As Char ' Text buffer. Must be global to be accessible from more threads.
    Dim RXCnt As Integer      ' Length of text buffer. Must be global too.
    Dim BusId As String
    Dim BId As Integer = 0
    Dim BusDis As String
    Dim DId As Integer = 0
    Dim code(4) As String
    Dim CId As Integer = 0
    Dim flag As Boolean = False
    Dim info As Boolean = False
    Dim ads As Boolean = False
    Dim cnt As Integer = 0
    Dim Adnum As Integer = 0
    Dim Adtot As Integer = 0
    Dim AdText As String
    Dim Adid(16) As String
    Dim Ad(16) As String
    Dim Adbus(16) As String
    Dim Adstation(16) As String
    Dim iklanbas As String
    Dim distance As Integer = 100
    ' Make a new System.IO.Ports.SerialPort instance, which is able to fire events.
    Dim WithEvents COMPort As New SerialPort

    Private Sub FullscreenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FullscreenToolStripMenuItem.Click
        If FullscreenToolStripMenuItem.Checked = False Then
            Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
            Me.WindowState = FormWindowState.Maximized
            Me.TopMost = True
            Me.FullscreenToolStripMenuItem.Checked = True
        Else
            Me.FormBorderStyle = Windows.Forms.FormBorderStyle.Sizable ' You can change this to the border style that you are currently using
            Me.WindowState = FormWindowState.Normal
            Me.TopMost = False
            Me.FullscreenToolStripMenuItem.Checked = False
        End If
    End Sub

    Private Sub Receiver(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles COMPort.DataReceived
        Dim data As String
        Do
            '----- Start of communication protocol handling -----------------------------------------------------------
            ' The code between the two lines does the communication protocol. In this case, it simply emties the
            '   receive buffer and converts it to text, but for all practical applications, you must replace this part
            '     with a code, which can collect one entire telegram by searching for the telegram
            '       delimiter/termination. In case of a simple ASCII protocol, you may just use ReadLine and receive
            '         in a global string instead of a byte array.
            ' Because this routine runs on a thread pool thread, it does not block the UI, so if you have any data
            '   convertion, encryption, expansion, error detection, error correction etc. to do, do it here.
            RXCnt = 0
            CId = 0


            Do
                If (RXCnt > 2000) Then
                    RXCnt = 0
                End If
                data = COMPort.ReadLine

                DataSplit(data)

                'Me.Invoke(New MethodInvoker(AddressOf Display)) ' Start "Display" on the UI thread

            Loop Until (COMPort.BytesToRead = 0)
            '----- End of communication protocol handling -------------------------------------------------------------

        Loop Until (COMPort.BytesToRead = 0)  ' Don't return if more bytes have become available in the meantime
    End Sub
    Private Sub Display()

    End Sub
    Private Sub PortSelection(ByVal sender As Object, ByVal e As EventArgs) Handles COMPortsBox.SelectedIndexChanged
        RTSLamp.BackColor = Color.Gray
        DTRLamp.BackColor = Color.Gray
        If COMPort.IsOpen Then
            COMPort.RtsEnable = False
            COMPort.DtrEnable = False
            ClosePort()
            ' NOTE. Because of the use of Invoke, the port should normally be closed from a different thread, see
            '   MaxiTesterClosing, but to ensure that the following delay works, this is not done in this case.
            ' Empty the message queue before the UI thread goes to sleep to update the modem lamps and the ComboBox.
            Application.DoEvents()
            Sleep(200)                      ' Wait 0.2 second for port to close as this does not happen immediately.
        End If
        COMPort.PortName = COMPortsBox.Text
        COMPort.BaudRate = 9600            ' Default for Max-i: 19200 bit/s, 8 data bits, no parity, 1 stop bit
        COMPort.WriteTimeout = 2000         ' Max time to wait for CTS = 2 sec.
        ' COMPort.ReadBufferSize = 16384      Necessary buffer size for 16C950 UART at 921.6 kbit/s
        Try
            COMPort.Open()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        BaudRateBox.Text = COMPort.BaudRate.ToString
        BitsBox.Text = COMPort.DataBits.ToString
        ParityBox.Text = COMPort.Parity.ToString
        FlowControlBox.Text = COMPort.Handshake.ToString
        If COMPort.IsOpen Then
            COMPort.RtsEnable = True
            RTSLamp.BackColor = Color.LightGreen
            COMPort.DtrEnable = True
            DTRLamp.BackColor = Color.LightGreen
        End If
    End Sub
    Private Sub MaxiTesterLoad(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        For Each COMString As String In My.Computer.Ports.SerialPortNames ' Load all available COM ports.
            COMPortsBox.Items.Add(COMString)
            'COMPortsBox.SelectedIndex = 0
        Next
        COMPortsBox.Sorted = True
        BaudRateBox.Items.Add("110")
        BaudRateBox.Items.Add("300")
        BaudRateBox.Items.Add("600")
        BaudRateBox.Items.Add("1200")
        BaudRateBox.Items.Add("1800")
        BaudRateBox.Items.Add("2400")
        BaudRateBox.Items.Add("4800")
        BaudRateBox.Items.Add("7200")
        BaudRateBox.Items.Add("9600")
        BaudRateBox.Items.Add("14400")
        BaudRateBox.Items.Add("19200")      ' Min. FIFO size 3 Bytes (8030 or 8530)
        BaudRateBox.Items.Add("38400")
        BaudRateBox.Items.Add("57600")      ' Min. FIFO size 8 bytes
        BaudRateBox.Items.Add("115200")     ' Min. FIFO size 16 bytes (16C550)
        BaudRateBox.Items.Add("230400")     ' Min. FIFO size 32 bytes (16C650)
        BaudRateBox.Items.Add("460800")     ' Min. FIFO size 64 bytes (16C750)
        BaudRateBox.Items.Add("921600")     ' Min. FIFO size 128 bytes (16C850 or 16C950)
        BaudRateBox.SelectedIndex = 8
        BitsBox.Items.Add("5")
        BitsBox.Items.Add("6")
        BitsBox.Items.Add("7")
        BitsBox.Items.Add("8")
        ParityBox.Items.Add("None")
        ParityBox.Items.Add("Odd")
        ParityBox.Items.Add("Even")
        ParityBox.Items.Add("Mark")         ' Leaves the parity bit set to 1
        ParityBox.Items.Add("Space")        ' Leaves the parity bit set to 0
        FlowControlBox.Items.Add("None")
        FlowControlBox.Items.Add("RequestToSend")
        FlowControlBox.Items.Add("RequestToSendXOnXOff")
        FlowControlBox.Items.Add("XOnXOff")
        RTSLamp.BackColor = Color.Gray
        DTRLamp.BackColor = Color.Gray
        CTSLamp.BackColor = Color.Gray
        DSRLamp.BackColor = Color.Gray
    End Sub
    Private Sub ClosePort()
        If COMPort.IsOpen Then COMPort.Close()
    End Sub

    ' This subroutine is activated when the form is closed. It closes the COM port. Without such a close command,
    '   the garbage collector may close the COM port while it is still in use!

    Private Sub MaxiTesterClosing(ByVal sender As Object, ByVal e As ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If MessageBox.Show("Do you really want to close the window", "", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then
            e.Cancel = True
        Else
            ' Close COM port on a new thread when the form is terminated with [X]
            Dim t As New Thread(AddressOf ClosePort)
            t.Start()
        End If
    End Sub

    ' This subroutine handles a change in Baud Rate.

    Private Sub BaudRateSelection(ByVal sender As Object, ByVal e As EventArgs) Handles BaudRateBox.SelectedIndexChanged
        COMPort.BaudRate = CInt(BaudRateBox.Text)
    End Sub

    ' This subroutine handles a change in number of data bits

    Private Sub DataBitsSelection(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BitsBox.SelectedIndexChanged
        COMPort.DataBits = CInt(BitsBox.Text)
    End Sub

    ' This subroutine handles a change in the parity.

    Private Sub ParitySelection(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ParityBox.SelectedIndexChanged
        COMPort.Parity = CType([Enum].Parse(GetType(Parity), ParityBox.Text), Parity)
    End Sub

    ' This subroutine handles a change in the flow control (handshake).

    Private Sub SoftwareFlowControlSelection(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FlowControlBox.SelectedIndexChanged
        COMPort.Handshake = CType([Enum].Parse(GetType(Handshake), FlowControlBox.Text), Handshake)
    End Sub

    ' This subroutine updates the modem control signal lamps

    Private Sub ModemLamps(ByVal sender As Object, ByVal e As SerialPinChangedEventArgs) Handles COMPort.PinChanged
        If COMPort.DsrHolding Then
            DSRLamp.BackColor = Color.LightGreen
        Else
            DSRLamp.BackColor = Color.Gray
        End If
        If COMPort.CtsHolding Then
            CTSLamp.BackColor = Color.LightGreen
        Else
            CTSLamp.BackColor = Color.Gray
        End If
    End Sub

    Private Sub Status(ByRef labstat As Object, ByVal bdis As String)
      

    End Sub



    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim returnstring As String
        Dim FileName As String
        returnstring = Space(127)
        'Replace d:\my box\MyMovie.avi with the AVI file you want to play
        FileName = "C:\Users\nzx\Videos\line0.avi"
        FileName = Chr(34) & FileName & Chr(34)
    End Sub

    Private Sub Timer5_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer5.Tick
        DataSplit("")

        Dim hour As Integer = DateTime.Now.Hour
        Dim min As Integer = DateTime.Now.Minute
        Dim sec As Integer = DateTime.Now.Second
        Dim day As Integer = DateTime.Now.Day
        Dim mon As Integer = DateTime.Now.Month
        Dim yr As Integer = DateTime.Now.Year


        Label7.Text = hour & " : " & min & " : " & sec & "        " & day & "/" & mon & "/" & yr
    End Sub

    Private Sub SendSerialData()
        ' Send strings to a serial port.
       


        For i As Integer = 0 To Adtot
            If Ad(i) <> Nothing Then

                COMPort.WriteLine(Adid(i) & " | " & Ad(i) & " | " & Adbus(i) & " | " & Adstation(i) & vbCrLf)

            End If
        Next

    End Sub

    Private Sub AdsSplit()
        Dim flag As Boolean = False
        Dim ind As Integer
        Dim i As Integer
        Dim fileIn As New StreamReader("ads.txt")
        Dim str As String = ""
        Dim lngCount As Long = 1
        Dim nofile As Integer = 0
        Dim temp(16) As String
        While (Not (fileIn.EndOfStream))
            If Adnum >= 16 Then
                Adnum = 0
            End If

            str = fileIn.ReadLine()
            If (str = "") Then
                Exit While
            End If

            If Not (flag) Then
                nofile = Convert.ToInt16(str)
                flag = True
                Continue While
            End If

            ind = str.IndexOf(":")
            Adid(i) = str.Substring(ind - 2, 2)
            str = str.Substring(ind + 1)

            '   If Adnum > 0 Then
            'For i As Integer = 0 To i
            'If (Adid(i) = Adid(Adnum)) Then

            'Continue While
            'End If
            'Next
            'End If

            ind = str.IndexOf(":")
            Ad(i) = str.Substring(0, ind)
            str = str.Substring(ind + 1)

            ind = str.IndexOf(":")
            Adbus(i) = str.Substring(0, ind)
            ' str = str.Substring(ind + 1)

            Adstation(i) = str.Substring(ind + 1)
            i = i + 1
            If i >= nofile Then
                Exit While
            End If
        End While
        Adtot = i
    End Sub
    Private Sub SaveData()
        Dim flag As Boolean = False
        Dim fileIn As New StreamWriter("ads.txt")
        Dim str As String = ""
        Dim lngCount As Long = 1
        Dim nofile As Integer = 0
        Dim temp(16) As String

        For i As Integer = 0 To Adtot
            fileIn.WriteLine(Adid(i) & " | " & Ad(i) & " | " & Adbus(i) & " | " & Adstation(i) & vbCrLf)
        Next
        fileIn.Close()
    End Sub
    Private Sub DataSplit(ByVal str As String)
        Dim flag As Boolean = False
        Dim ind As Integer
        Dim nofile As Integer = 0
        
        If Adnum >= 16 Then
            Adnum = 0
        End If

        If (str <> "") Then

            ind = str.IndexOf("|")
            Adid(Adtot) = str.Substring(ind - 3, 2)
            str = str.Substring(ind + 1)

            ind = str.IndexOf("|")
            Ad(Adtot) = str.Substring(0, ind)
            str = str.Substring(ind + 1)

            ind = str.IndexOf("|")
            Adbus(Adtot) = str.Substring(0, ind)
            ' str = str.Substring(ind + 1)
            Adstation(Adtot) = str.Substring(ind + 1)

            If Adid(Adtot).Contains("XX") Then
                For j As Integer = 0 To Adtot - 1
                    If Ad(Adtot) = Ad(j) Then

                        Dim i As Long
                        For i = j To UBound(Adid) - 1
                            Adid(i) = Adid(i + 1)
                        Next i
                        ReDim Preserve Adid(UBound(Adid) - 1)

                        For i = j To UBound(Ad) - 1
                            Ad(i) = Ad(i + 1)
                        Next i
                        ReDim Preserve Ad(UBound(Ad) - 1)

                        For i = j To UBound(Adbus) - 1
                            Adbus(i) = Adbus(i + 1)
                        Next i
                        ReDim Preserve Adbus(UBound(Adbus) - 1)

                        For i = j To UBound(Adstation) - 1
                            Adstation(i) = Adstation(i + 1)
                        Next i
                        ReDim Preserve Adstation(UBound(Adstation) - 1)


                    End If
                Next
                Adtot = Adtot - 1
                Me.Invoke(New MethodInvoker(AddressOf cleartext))
                'SaveData()
            Else

            End If
            Adtot = Adtot + 1
        End If
    End Sub
  
    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        Label14.Location = New Point(70, 70)
        Label14.Font = New Font(Label14.Font.FontFamily, 50, Label14.Font.Style)
        If cnt > 5 Then
            cnt = 0
        End If

        Select Case cnt
            Case 0
                Label14.Text = "Seoul Express Bus Terminal"
                cnt = cnt + 1
                'Transfer iklan data dari busstop ke bus kat sini
                Exit Select
            Case 1
                Label14.Text = "Seocho Subway"
                Timer4.Start()
                'cnt = cnt + 1
                'Transfer iklan data pd busstop kat sini
                'SendSerialData()
                Exit Select
            Case 2
                Label14.Text = "Seolleung Subway"
                cnt = cnt + 1
                Exit Select
            Case 3
                Label14.Text = "COEX Mall"
                cnt = cnt + 1
                Exit Select
            Case 4
                Label14.Text = "Apgujeong-dong"
                cnt = cnt + 1
                Exit Select
            Case 5
                Label14.Text = "Sin sa-dong"
                cnt = cnt + 1
                Exit Select
            Case 6
                Exit Select

        End Select

    End Sub
    Private Sub cleartext()
        TextBox1.Clear()
        TextBox2.Clear()
    End Sub

    Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer3.Tick
        If Adnum >= Adtot Then
            Adnum = 0
        End If
       
        If (Adnum < Adtot) Then
            If Adid(Adnum).Contains("XX") Then
                Adnum = Adnum + 1
                Exit Sub
            End If
            If (Adid(Adnum).Contains("N")) Then

                TextBox1.Text = Ad(Adnum) & vbCrLf
                TextBox1.AppendText("Bus: " & Adbus(Adnum) & vbCrLf)
                TextBox1.AppendText("Station: " & Adstation(Adnum))
                Adnum = Adnum + 1
            Else
                TextBox2.Text = Ad(Adnum) & vbCrLf
                TextBox2.AppendText("Bus: " & Adbus(Adnum) & vbCrLf)
                TextBox2.AppendText("Station: " & Adstation(Adnum))
                Adnum = Adnum + 1
            End If
        End If

    End Sub

    Private Sub Timer4_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer4.Tick
        distance = distance - 10
        If distance < 50 Then
            If distance < 10 Then
                distance = 100
                cnt = cnt + 1
                SendSerialData()
                Timer4.Stop()
                Exit Sub
            Else
                If COMPort.IsOpen Then
                    COMPort.WriteLine("ZZ" & distance)

                End If
            End If
        End If
 
        

    End Sub

End Class
